# coding:utf-8

import warnings

import numpy as np
import pandas as pd

warnings.filterwarnings("ignore")
import pickle
import os
os.chdir('script/')

def load_model(data):
    # 读取训练好的模型、变量文件
    f = open('lgb.pkl', 'rb')
    lgb = pickle.load(f)
    f.close()
    f = open('feature_selection_lgb_68.pkl', 'rb')
    allFeatures = pickle.load(f)
    f.close()
    A = 500
    PDO = 20
    B = PDO / np.log(2)
    y_value = pd.Series(lgb.predict(data[allFeatures]))
    y_value = y_value.apply(lambda x: 0.9999 if x >= 0.99999 else x)
    score = [int(A + B * (-np.log(i / (1 - i)))) for i in y_value]
    order_id_df = data['订单号']
    channel_df=data['产品']
    score_df = pd.DataFrame(score, columns=['score'])
    prob_df = pd.DataFrame(list(y_value), columns=['prob_value'])
    score_card = pd.concat([order_id_df,channel_df, score_df, prob_df], axis=1)
    list_data = []
    for row in score_card.to_dict('records'):
        if isinstance(row['订单号'], str):
            dict = {}
            dict['orderId'] = row['订单号']
            dict['score'] = row['score']
            dict['prob_value'] = row['prob_value']
            dict['channel']=row['产品']
            list_data.append(dict)

    return list_data


def load_model_re(data):
    # 读取训练好的模型、变量文件
    f = open('lgb_reloan.pkl', 'rb')
    lgb = pickle.load(f)
    f.close()
    f = open('feature_selection_lgb_56_reloan.pkl', 'rb')
    allFeatures = pickle.load(f)
    f.close()
    A = 500
    PDO = 20
    B = PDO / np.log(2)
    y_value = pd.Series(lgb.predict(data[allFeatures]))
    y_value = y_value.apply(lambda x: 0.9999 if x >= 0.99999 else x)
    score = [int(A + B * (-np.log(i / (1 - i)))) for i in y_value]
    order_id_df = data['订单号']
    channel_df=data['产品']
    score_df = pd.DataFrame(score, columns=['score'])
    prob_df = pd.DataFrame(list(y_value), columns=['prob_value'])
    score_card = pd.concat([order_id_df,channel_df, score_df, prob_df], axis=1)
    list_data = []
    for row in score_card.to_dict('records'):
        if isinstance(row['订单号'], str):
            dict = {}
            dict['orderId'] = row['订单号']
            dict['score'] = row['score']
            dict['prob_value'] = row['prob_value']
            dict['channel']=row['产品']
            list_data.append(dict)

    return list_data







